package com.CatTalkApi.Servlet;

import com.CatTalkApi.DAO.DataBaseContext;
import com.CatTalkApi.DAO.Passage;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/GetPassageByID")
public class GetPassageByID extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Content-Type", "application/json;");

        System.out.println("Get Passage Method: " + req.getMethod());
        //配置跨域
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH");
        resp.setHeader("Access-Control-Allow-Headers", "authorization, content-type,token,identify");
        resp.setHeader("Access-Control-Expose-Headers", "X-forwared-port, X-forwarded-host");
        resp.setHeader("Vary", "Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
        super.service(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ResultSet resultSet = null;
        Passage passage = null;
        try {
            String sql = "SELECT * FROM `passage` WHERE `passage`.Passage_ID = %s";
            resultSet = DataBaseContext.getInstance().GetStmt().executeQuery(String.format(sql, req.getParameter("id")));
            passage = new Passage();
            while (resultSet.next()) {
                passage.Id = resultSet.getInt(1);
                passage.Title = resultSet.getString(4);
                passage.Body = resultSet.getString(3);
                passage.UsrId = resultSet.getInt(2);
            }
            resultSet.close();
            DataBaseContext.getInstance().Close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        if (passage != null) {
            resp.getWriter().write(JSON.toJSONString(passage));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
